﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;
using SSG.Tools;

namespace SSG.Model
{
    /// <summary>
    /// Group of airports
    /// </summary>
    [Serializable]
    public class AirportsGroup
    {
        /// <summary>
        /// Default constructor, for serialization
        /// </summary>
        public AirportsGroup()
        {
            this.Icaos = new List<string>();
        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="name"></param>
        public AirportsGroup(string name) : this()
        {
            if (String.IsNullOrEmpty(name)) throw new ArgumentNullException("name");
            this.Name = name;
        }

        /// <summary>
        /// Airports in group
        /// </summary>
        [XmlIgnore]
        public List<Airport> Airports { get { return this.GetAirports(); } }

        /// <summary>
        /// Name of the group
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// ICAO codes of Airports in group
        /// </summary>
        public List<string> Icaos { get; private set; }

        /// <summary>
        /// Airports
        /// </summary>
        /// <returns></returns>
        private List<Airport> GetAirports()
        {
            return Airport.Airports.FindAll(ap => this.Icaos.Contains(ap.Name)).ToList();
        }

        /// <summary>
        /// Valid group name
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static bool IsValidGroupName(string name)
        {
            if (String.IsNullOrEmpty(name)) return false;
            if (name.Length > 25) return false;
            if (name.Contains(' ')) return false;
            return true;
        }

        /// <summary>
        /// Find ICAO code in candidates group
        /// </summary>
        /// <param name="icao"></param>
        /// <param name="candidateGroups"></param>
        /// <returns></returns>
        public static AirportsGroup FindInGroups(string icao, List<AirportsGroup> candidateGroups)
        {
            if (candidateGroups.NullSafeIsEmpty()) return null;
            return String.IsNullOrEmpty(icao) ? null : candidateGroups.FirstOrDefault(ag => ag.Icaos.Contains(icao));
        }
    }
}